<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <%- include("./component/header.html"); %>
    <style>
        #container-controls {
            display: grid;
            grid-template-columns: auto 1fr;
            gap: 20px;
            place-items: center right;
        }

        #container-controls>.form-labels {
            font-size: 1.05em;
            font-family: cursive;
        }

        #container-controls>.form-elements {
            height: 30px;
            width: 100%;
            font-size: 18px;
        }

        #container-submit {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            padding: 0 30%;
            margin-top: 30px;
        }

        .btn {
            height: 30px;
        }
    </style>
</head>
<body>
    <%- include("./component/navbar.html"); %>
    <main class="main">
        <h1><%= title %></h1>
        <% if (typeof(subpage) !== "undefined") { %>
        <p><a href="<%= pageUrl %>../">返回上一级</a></p>
        <% } %>
        <div id="container">
            <div id="container-controls">页面加载中，请稍候 ...</div>
            <div id="container-submit">
                <button class="btn" id="btn-submit">提交</button>
                <button class="btn" id="btn-clear" disabled="true">清空</button>
            </div>
        </div>
    </main>
    <!-- 获取参数 -->
    <script src="/assets/javascripts/getParams.js"></script>
    <!-- 验证组件用户输入值 -->
    <script src="/assets/javascripts/dashboard/getValidateUtils.js"></script>
    <!-- 渲染组件 -->
    <script src="/assets/javascripts/dashboard/renderFormControls.js"></script>
    <% if ( pageTemplate != "" ) { %>
        <!-- 引入对应页面渲染配置 -->
        <%- include(pageTemplate); %>
    <% } %>
    <!-- 进行渲染 -->
    <script>
        var group = '<%= group %>';
        var page = '<%= page %>';
        var title = '<%= title %>';
        var controlsProfile = {};

        async function renderFormControlsFunc() {
            // 获取将要渲染的 Controls
            controlsProfile = await getControlsProfile(getValidateUtils);

            // 渲染控件
            var formControls = renderFormControls({ Controls: controlsProfile });
            console.log(formControls);

            // 将控件填充到网页上
            var containerControls = document.getElementById('container-controls');
            containerControls.innerHTML = "";
            formControls.forEach(function (item) {
                containerControls.appendChild(item.label);
                containerControls.appendChild(item.control);
            });
        }

        // 渲染控件
        renderFormControlsFunc();

        // 提交表单事件
        function formSubmit({
            type = 'POST',
            url = '',
            data = {},
            success = (response) => { console.log(response) }
        }) {
            var data = data || {};
            for (var i = 0; i < controlsProfile.length; i++) {
                const controlsProfileItem = controlsProfile[i];
                var control = document.getElementById(controlsProfileItem.attr.id);
                // 判断 control 是否为空
                if (!control) {
                    swal("控件不存在：" + controlsProfileItem.attr.id);
                    return;
                }
                var name = control.name;
                var value = control.value;
                // console.log("name:", name, "value:", value, "control:", control);
                var validateResult = controlsProfileItem.validate(value);
                if (validateResult.result) {
                    data[name] = value;
                } else {
                    swal(validateResult.msg).then(function () {
                        control.focus();
                    });
                    return;
                }
            }
            // var controls = document.getElementsByClassName('form-elements');
            // for (var i = 0; i < controls.length; i++) {
            //     var control = controls[i];
            //     var name = control.name;
            //     var value = control.value;
            //     data[name] = value;
            // }
            // 添加管理员 token 信息
            data['token'] = localStorageUtils.getToken();
            console.log(data);

            postRequest(url, data)
                .then(function (responseData) {
                    var axiosData = responseData.data;
                    var status = axiosData.status;
                    var data = axiosData.data;
                    if (status === "success") {
                        success(data);
                    } else {
                        swal(`出错啦！${data.errMsg} (错误码: ${data.errCode})`).then(function () {
                            if (data.errCode == "20004") {
                                // 登录过期
                                localStorageUtils.userLogout();
                                location.href = "/login?redirect=" + encodeURIComponent(location.pathname + location.search);
                            }
                        });
                    }
                }).catch(function (error) {
                    console.log(error);
                    swal("无法连接到服务器，请检查网络连接！");
                }).finally(function () {
                    $("#favorties-button").css("visibility", "visible");
                });
        }

        // 绑定提交按钮事件
        $("#btn-submit").click(btnSubmitClick);
    </script>
    <%- include("./component/footer.html"); %>
</body>
</html>